<template>
  <view class="consultation-add-container">
    <view class="page-header">
      <text class="page-title">新增在线问诊</text>
      <text class="page-subtitle">创建新的问诊记录</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">问诊信息</text>
        
        <view class="form-item">
          <text class="form-label required">患者ID</text>
          <uni-easyinput 
            v-model="formData.patient_id"
            placeholder="请输入患者ID"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.patient_id" class="error-text">{{ errors.patient_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">医生ID</text>
          <uni-easyinput 
            v-model="formData.doctor_id"
            placeholder="请输入医生ID"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.doctor_id" class="error-text">{{ errors.doctor_id }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">问诊内容</text>
        
        <view class="form-item">
          <text class="form-label required">问题描述</text>
          <textarea 
            v-model="formData.question" 
            class="form-textarea" 
            placeholder="请详细描述您的症状和问题"
            maxlength="1000"
          />
          <text v-if="errors.question" class="error-text">{{ errors.question }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">附件（图片/文件）</text>
          <uni-file-picker 
            v-model="attachmentsFileList"
            file-mediatype="all"
            mode="list"
            :limit="9"
            :auto-upload="false"
            @select="handleAttachmentsSelect"
            @delete="handleAttachmentDelete"
          />
          <text class="form-hint">最多上传9个文件</text>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

const formData = reactive({
  patient_id: '',
  doctor_id: '',
  question: '',
  attachments: [],
  answer: '',
  status: 0
})

const errors = reactive({
  patient_id: '',
  doctor_id: '',
  question: ''
})

const attachmentsFileList = ref([])

function handleAttachmentsSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    attachmentsFileList.value = e.tempFiles
  }
}

function handleAttachmentDelete(e) {
  // File picker handles deletion automatically
}

async function uploadAttachmentsToCloud() {
  if (!attachmentsFileList.value || attachmentsFileList.value.length === 0) {
    return []
  }
  
  try {
    const uploadPromises = attachmentsFileList.value
      .filter(file => file.path && !file.url)
      .map(async (file) => {
        const uploadResult = await uniCloud.uploadFile({
          filePath: file.path,
          cloudPath: `consultations/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.name.split('.').pop()}`
        })
        return uploadResult.fileID
      })
    
    const fileUrls = await Promise.all(uploadPromises)
    
    const existingUrls = attachmentsFileList.value
      .filter(file => file.url && !file.path)
      .map(file => file.url)
    
    return [...existingUrls, ...fileUrls]
  } catch (err) {
    console.error('附件上传失败:', err)
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.patient_id || formData.patient_id.trim().length === 0) {
    errors.patient_id = '请输入患者ID'
    isValid = false
  } else {
    errors.patient_id = ''
  }
  
  if (!formData.doctor_id || formData.doctor_id.trim().length === 0) {
    errors.doctor_id = '请输入医生ID'
    isValid = false
  } else {
    errors.doctor_id = ''
  }
  
  if (!formData.question || formData.question.trim().length === 0) {
    errors.question = '请输入问题描述'
    isValid = false
  } else {
    errors.question = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    let attachmentUrls = []
    if (attachmentsFileList.value && attachmentsFileList.value.length > 0) {
      uni.showLoading({ title: '上传附件中...' })
      attachmentUrls = await uploadAttachmentsToCloud()
    }
    
    const submitData = {
      ...formData,
      attachments: attachmentUrls
    }
    
    // 调用云对象方法创建咨询（会自动挂载 hospital_id）
    const consultationsObj = uniCloud.importObject('dh-consultations')
    const result = await consultationsObj.createConsultation(submitData)
    
    uni.hideLoading()
    
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/consultations/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '创建失败', icon: 'none' })
    }
  } catch (err) {
    console.error('创建失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/consultations/list' })
}
</script>

<style lang="scss" scoped>
.consultation-add-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.form-textarea {
  width: 100%;
  min-height: 300rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
